﻿using System;
using UnityEngine;

namespace QFramework
{
    public interface IItemKitLoader
    {
        ItemDatabase LoadDatabase(string databaseName);
        ItemLanguagePackage LoadLanguagePackage(string languagePackageName);
        
        /// <summary>
        /// 异步加载
        /// </summary>
        /// <param name="databaseName"></param>
        /// <param name="onLoadFinish"></param>
        void LoadItemDatabaseAsync(string databaseName, Action<ItemDatabase> onLoadFinish);
        void LoadItemLanguagePackageAsync(string languagePackageName, Action<ItemLanguagePackage> onLoadFinish);
    }

    /// <summary>
    /// 默认的Item资源加载器
    /// </summary>
    public class DefaultItemKitLoader : IItemKitLoader
    {
        /// <summary>
        /// 加载Item数据
        /// </summary>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public ItemDatabase LoadDatabase(string databaseName)
        {
            return Resources.Load<ItemDatabase>(databaseName);
        }

        /// <summary>
        /// 加载语言包
        /// </summary>
        /// <param name="languagePackageName"></param>
        /// <returns></returns>
        public ItemLanguagePackage LoadLanguagePackage(string languagePackageName)
        {
            return Resources.Load<ItemLanguagePackage>(languagePackageName);
        }

        /// <summary>
        /// 异步加载Item数据
        /// </summary>
        /// <param name="databaseName"></param>
        /// <param name="onLoadFinish"></param>
        public void LoadItemDatabaseAsync(string databaseName, Action<ItemDatabase> onLoadFinish)
        {
            var request = Resources.LoadAsync<ItemDatabase>(databaseName);
            request.completed += operation =>
            {
                onLoadFinish(request.asset as ItemDatabase);
            };
        }

        /// <summary>
        /// 异步加载语言包
        /// </summary>
        /// <param name="languagePackageName"></param>
        /// <param name="onLoadFinish"></param>
        public void LoadItemLanguagePackageAsync(string languagePackageName, Action<ItemLanguagePackage> onLoadFinish)
        {
            var request = Resources.LoadAsync<ItemDatabase>(languagePackageName);
            request.completed += operation =>
            {
                onLoadFinish(request.asset as ItemLanguagePackage);
            };
        }
    }
}